package com.zz.wechat.util;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import javax.net.ssl.HttpsURLConnection;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.MessageDigest;
import java.util.*;

/**
 * Created by Bsea
 * 2017-06-11 19:12
 */

/*
'============================================================================
'api说明：
'createSHA1Sign创建签名SHA1
'getSha1()Sha1签名
'============================================================================
'*/
public class Sha1Util {
	
	public static String getjsApiTicket(String url,String assess_token) throws ClientProtocolException, IOException {
		String ticket="";
		URL url2=new URL(url+assess_token+"&type=jsapi");
		HttpsURLConnection con=(HttpsURLConnection) url2.openConnection();
		con.setRequestMethod("GET");
		con.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); 
		con.setDoOutput(true); 
		con.setDoInput(true);
		con.connect();
		InputStream input=con.getInputStream();
		byte[] c=new byte[input.available()];
		input.read(c);
		// String有一个构造方法，可以接受一个，字节的数组，来创建一个String.
		//这个过程，就实现了，字节数组转化为String的过程。
		String message=new String(c,"UTF-8");
		input.close();
		con.disconnect();
		
		JSONObject demoJson;
		try {
			demoJson = new JSONObject(message);
			ticket=demoJson.getString("ticket");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return ticket;
		
	}
	public static String getNonceStr() {
		Random random = new Random();
		return MD5Util.MD5Encode(String.valueOf(random.nextInt(10000)), "UTF-8");
	}
	public static String getTimeStamp() {
		return String.valueOf(System.currentTimeMillis() / 1000);
	}
	
   //创建签名SHA1
	public static String createSHA1Sign(SortedMap<String, String> signParams) throws Exception {
		StringBuffer sb = new StringBuffer();
		Set es = signParams.entrySet();
		Iterator it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			sb.append(k + "=" + v + "&");
			//要采用URLENCODER的原始值！
		}
		String params = sb.substring(0, sb.lastIndexOf("&"));
		return getSha1(params);
	}
	//Sha1签名
	public static String getSha1(String str) {
		if (str == null || str.length() == 0) {
			return null;
		}
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f' };

		try {
			MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
			mdTemp.update(str.getBytes("UTF-8"));
			byte[] md = mdTemp.digest();
			int j = md.length;
			char buf[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
				buf[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(buf);
		} catch (Exception e) {
			return null;
		}
	}
	public static String getAccessToken() throws IOException{
		String accessToken="";
		String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx4c77158b3d5d5ca7&secret=2f41aced533b3f5b1e32bbd6534b97b8";
		URL url2=new URL(url);
		HttpsURLConnection con=(HttpsURLConnection) url2.openConnection();
		con.setRequestMethod("GET");
		con.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); 
		con.setDoOutput(true); 
		con.setDoInput(true);
		
		con.connect();
		InputStream input=con.getInputStream();
		byte[] c=new byte[input.available()];
		input.read(c);
		// String有一个构造方法，可以接受一个，字节的数组，来创建一个String.
		//这个过程，就实现了，字节数组转化为String的过程。
		String message=new String(c,"UTF-8");
		input.close();
		con.disconnect();
		
		JSONObject demoJson;
		try {
			demoJson = new JSONObject(message);
			accessToken=demoJson.getString("access_token");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return accessToken;
		
	}
	public static void main(String[] args) throws Exception {
		SortedMap<String, String> finalpackage = new TreeMap<String, String>();
		String timestamp = Sha1Util.getTimeStamp();
		String NonceStr=getNonceStr();
		WeiChatUtil wu=new WeiChatUtil();
//		WeiChatConfig.accesstoken=wu.getAccessToken();
		//String accesstoken=wu.getAccessToken();
		String accesstoken=WeiChatConfig.accesstoken;
		System.out.println("accesstoken======"+accesstoken);
		String Ticket=getjsApiTicket("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=",wu.getAccessToken());
		//finalpackage.put("appId", WeiChatConfig.appid);
		System.out.println("timestamp========"+timestamp);
		System.out.println("NonceStr======"+NonceStr);
		System.out.println("Ticket======="+Ticket);
		finalpackage.put("timestamp", timestamp);
		finalpackage.put("noncestr", NonceStr);
		finalpackage.put("jsapi_ticket", Ticket);
		finalpackage.put("url", "http://h1882979h5.iask.in/weichat/weichatinit-bsea.html");
		//finalpackage.put("package", packages);

		//finalpackage.put("signType", WeiChatConfig.signType);

		String signature =Sha1Util.createSHA1Sign(finalpackage);
		System.out.println("signature=="+signature);
		//System.out.println(getSha1("jsapi_ticket="+Ticket+"&noncestr="+NonceStr+"&timestamp="+timestamp+"&url=http://b50e7411.ngrok.io/weichat/hc/weichatinit-hc.html/"));
	}
}
